package com.lim.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import com.lim.bean.Result;
import com.lim.bean.weather_data;
/**
 * <p>Title: WeatherFreeApiUtil</p>
 * <p>Description:  数据来源 （ http://developer.baidu.com/map/carapi-7.htm） </p>
 * <p>Copyright: Copyright (c) 2014</p>
 * <p>Company: cnTomorrow</p>
 * @author Lyijiao
 * @version 1.0
 */
public class WeatherFreeApiUtil {

	private static String readAll(Reader rd) throws IOException {
	    StringBuilder sb = new StringBuilder();
	    int cp;
	    while ((cp = rd.read()) != -1) {
	      sb.append((char) cp);
	    }
	    return sb.toString();
	  }

	  public static String readJsonFromUrl(String url) throws IOException, JSONException {
	    InputStream is = new URL(url).openStream();
	    try {
	      BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
	      String jsonText = readAll(rd);
	      return jsonText;
	    } finally {
	      is.close();
	     // System.out.println("同时 从这里也能看出 即便return了，仍然会执行finally的！");
	    }
	  }
	  public static void main(String[] args) throws IOException, JSONException {
		  //这里调用百度的ip定位api服务 详见 http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm
	    String json = readJsonFromUrl("http://api.map.baidu.com/telematics/v3/weather?location=张家口|北京&output=json&ak=4f826abdeb2fe823f9e62fa7f62cdd71");
	    System.out.println(json);
	    JSONObject jsonObj= JSONObject.fromObject(json);
	    if(XString.equals(jsonObj.getString("status"),"success")){
	    	JSONArray results= jsonObj.getJSONArray("results");
	    	for(int i=0;i<results.size();i++){
		    	JSONObject obj=results.getJSONObject(i);
		    	 Map<String,Object> classMap = new HashMap<String,Object>();  
		         classMap.put("result", Result.class);  
		         classMap.put("weather_data", weather_data.class);  
		         //使用暗示，直接将json解析为指定自定义对象 
		         Result result = (Result)JSONObject.toBean(obj,Result.class , classMap);
		    	//Result result= (Result) JSONObject.toBean(results0,Result.class);
		         System.out.println();
		    	System.out.print(result.getCurrentCity());
		    	System.out.print(result.getWeather_data().get(0).getWeather());
		    	System.out.print(result.getWeather_data().get(0).getTemperature());
		    	System.out.print(result.getWeather_data().get(0).getWind());
	    	}
	    } 
	  }
}
